package com.chen.recruit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chen.recruit.common.api.CommonResult;
import com.chen.recruit.common.constants.MessageConstants;
import com.chen.recruit.common.enums.CommonStatus;
import com.chen.recruit.domain.User;
import com.chen.recruit.mapper.UserMapper;
import com.chen.recruit.service.PostService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.chen.recruit.domain.Post;
import com.chen.recruit.mapper.PostMapper;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 岗位信息Service业务层处理
 *
 * @author cgy
 * @date 2022-08-19
 */
@Service
@RequiredArgsConstructor
public class PostServiceImpl extends ServiceImpl<PostMapper, Post> implements PostService {

    private final UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult addOrUpdatePost(Post post) {
        boolean exists = baseMapper.exists(Wrappers.<Post>lambdaQuery()
                .eq(StringUtils.isNotBlank(post.getName()), Post::getName, post.getName())
                .ne(ObjectUtil.isNotNull(post.getId()), Post::getId, post.getId()));
        if (exists) {
            return CommonResult.fail(MessageConstants.POST_NAME_EXIST);
        }
        if (ObjectUtil.isNotNull(post.getId()) && checkPostIsUse(post.getId())
                && post.getStatus() == CommonStatus.DISABLE) {
            return CommonResult.fail(MessageConstants.UPDATE_POST_STATUS_FAIL);
        }
        return this.saveOrUpdate(BeanUtil.toBean(post, Post.class)) ? CommonResult.success() : CommonResult.fail();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult deletePostByIds(Integer[] ids) {
        if (checkPostIsUse(ids)) {
            return CommonResult.fail(MessageConstants.DELETE_POST_FAIL);
        }
        return this.removeByIds(Arrays.asList(ids)) ? CommonResult.success() : CommonResult.fail();
    }

    private boolean checkPostIsUse(Integer... ids) {
        return userMapper.exists(Wrappers.<User>lambdaQuery().in(User::getPostId, ids));
    }

}
